package com.jk.myimkit.imkit.plugin.location;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;

import com.jk.myimkit.R;
import com.jk.myimkit.imageloader.core.DisplayImageOptions;
import com.jk.myimkit.imageloader.core.DisplayImageOptions.Builder;
import com.jk.myimkit.imageloader.core.ImageLoader;
import com.jk.myimkit.imageloader.core.assist.LoadedFrom;
import com.jk.myimkit.imageloader.core.display.CircleBitmapDisplayer;
import com.jk.myimkit.imageloader.core.imageaware.ImageViewAware;
import com.jk.myimkit.imageloader.core.listener.ImageLoadingListener;
import com.jk.myimkit.imageloader.core.listener.ImageLoadingProgressListener;
import com.jk.myimkit.imkit.RongBaseNoActionbarActivity;
import com.jk.myimkit.imkit.utilities.PromptPopupDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import io.rong.common.RLog;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.location.RealTimeLocationConstant;
import io.rong.imlib.model.UserInfo;

public class AMapRealTimeActivity extends RongBaseNoActionbarActivity implements ILocationChangedListener, IUserInfoProvider.UserInfoCallback {
    private static final String TAG = "AMapRealTimeActivity";
    private MapView mAMapView;
    private ViewGroup mTitleBar;
    private TextView mUserText;
    private Handler mHandler;
    private AMap mAMap;
    private Map<String, UserTarget> mUserTargetMap;
    private ArrayList<String> mParticipants;
    private boolean mHasAnimate;

    public AMapRealTimeActivity() {
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.rc_location_real_time_activity);
        this.mHandler = new Handler();
        this.mUserTargetMap = new HashMap();
        this.mAMapView = (MapView)this.findViewById(R.id.rc_ext_amap);
        this.mAMapView.onCreate(savedInstanceState);
        View exitView = this.findViewById(R.id.rc_toolbar_close);
        exitView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                PromptPopupDialog dialog = PromptPopupDialog.newInstance(v.getContext(), "", AMapRealTimeActivity.this.getString(R.string.rc_ext_exit_location_sharing), AMapRealTimeActivity.this.getString(R.string.rc_ext_exit_location_sharing_confirm));
                dialog.setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                    public void onPositiveButtonClicked() {
                        LocationManager.getInstance().quitLocationSharing();
                        AMapRealTimeActivity.this.finish();
                    }
                });
                dialog.show();
            }
        });
        View closeView = this.findViewById(R.id.rc_toolbar_hide);
        closeView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AMapRealTimeActivity.this.finish();
            }
        });
        this.mTitleBar = (ViewGroup)this.findViewById(R.id.rc_user_icons);
        this.mUserText = (TextView)this.findViewById(R.id.rc_user_text);
        this.mParticipants = this.getIntent().getStringArrayListExtra("participants");
        if (this.mParticipants == null) {
            this.mParticipants = new ArrayList();
            this.mParticipants.add(RongIMClient.getInstance().getCurrentUserId());
        }

        this.initMap();
        LocationManager.getInstance().setLocationChangedListener(this);
        LocationManager.getInstance().setMyLocationChangedListener(new IMyLocationChangedListener() {
            public void onMyLocationChanged(AMapLocationInfo locInfo) {
                AMapRealTimeActivity.this.updateParticipantMarker(locInfo.getLat(), locInfo.getLng(), RongIMClient.getInstance().getCurrentUserId());
            }
        });
        LocationManager.getInstance().updateMyLocationInLoop(5);
    }

    private void initMap() {
        this.mAMap = this.mAMapView.getMap();
        this.mAMap.getUiSettings().setMyLocationButtonEnabled(false);
        this.mAMap.setMapType(1);
        Iterator var1 = this.mParticipants.iterator();

        while(var1.hasNext()) {
            String userId = (String)var1.next();
            AMapRealTimeActivity.UserTarget userTarget = this.createUserTargetById(userId);
            this.mUserTargetMap.put(userId, userTarget);
            LocationManager.getInstance().getUserInfo(userId, this);
            this.updateParticipantTitleText();
        }

        CameraUpdate zoom = CameraUpdateFactory.zoomTo(17.0F);
        this.mAMap.animateCamera(zoom, (AMap.CancelableCallback)null);
    }

    public void onGotUserInfo(UserInfo userInfo) {
        String userId = userInfo.getUserId();
        AMapRealTimeActivity.UserTarget userTarget = (AMapRealTimeActivity.UserTarget)this.mUserTargetMap.get(userId);
        if (userTarget != null) {
            this.setAvatar(userTarget.targetView, userInfo.getPortraitUri() != null ? userInfo.getPortraitUri().toString() : null);
            View iconView = LayoutInflater.from(this).inflate(R.layout.rc_icon_rt_location_marker, (ViewGroup)null);
            ImageView imageView = (ImageView)iconView.findViewById(16908294);
            ImageView locImageView = (ImageView)iconView.findViewById(16908295);
            this.setAvatar(imageView, userInfo.getPortraitUri() != null ? userInfo.getPortraitUri().toString() : null);
            if (userId.equals(RongIMClient.getInstance().getCurrentUserId())) {
                locImageView.setImageResource(R.drawable.rc_rt_loc_myself);
            } else {
                locImageView.setImageResource(R.drawable.rc_rt_loc_other);
            }

            userTarget.targetMarker.setIcon(BitmapDescriptorFactory.fromView(iconView));
        }

    }

    public void onLocationChanged(double latitude, double longitude, String userId) {
        this.updateParticipantMarker(latitude, longitude, userId);
    }

    public void onParticipantJoinSharing(String userId) {
        if (this.mUserTargetMap.get(userId) == null) {
            if (!this.mParticipants.contains(userId)) {
                this.mParticipants.add(userId);
            }

            AMapRealTimeActivity.UserTarget userTarget = this.createUserTargetById(userId);
            this.mUserTargetMap.put(userId, userTarget);
            LocationManager.getInstance().getUserInfo(userId, this);
            this.updateParticipantTitleText();
        }
    }

    public void onParticipantQuitSharing(String userId) {
        AMapRealTimeActivity.UserTarget userTarget = (AMapRealTimeActivity.UserTarget)this.mUserTargetMap.get(userId);
        this.mParticipants.remove(userId);
        if (userTarget != null) {
            this.mUserTargetMap.remove(userId);
            this.removeParticipantTitleIcon(userTarget);
            this.updateParticipantTitleText();
            this.removeParticipantMarker(userTarget);
        }

    }

    public void onError(RealTimeLocationConstant.RealTimeLocationErrorCode code) {
        Toast.makeText(this, R.string.rc_network_exception, Toast.LENGTH_SHORT).show();
        LocationManager.getInstance().quitLocationSharing();
        this.finish();
    }

    public void onSharingTerminated() {
    }

    private DisplayImageOptions createDisplayImageOptions(int defaultResId) {
        Builder builder = new Builder();
        if (defaultResId != 0) {
            Drawable defaultDrawable = this.getResources().getDrawable(defaultResId);
            builder.showImageOnLoading(defaultDrawable);
            builder.showImageForEmptyUri(defaultDrawable);
            builder.showImageOnFail(defaultDrawable);
        }

        builder.displayer(new CircleBitmapDisplayer());
        DisplayImageOptions options = builder.resetViewBeforeLoading(false).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        return options;
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    private void setAvatar(ImageView imageView, String url) {
        DisplayImageOptions options = this.createDisplayImageOptions(url == null ? R.drawable.rc_ext_realtime_default_avatar : 0);
        ImageViewAware imageViewAware = new ImageViewAware(imageView);
        if (url == null) {
            Drawable drawable = options.getImageForEmptyUri((Resources)null);

            try {
                Bitmap bitmap = this.drawableToBitmap(drawable);
                options.getDisplayer().display(bitmap, imageViewAware, LoadedFrom.DISC_CACHE);
            } catch (Exception var9) {
                var9.printStackTrace();
            }
        } else {
            File file = ImageLoader.getInstance().getDiskCache().get(url);
            if (file == null && !TextUtils.isEmpty(url)) {
                ImageLoader.getInstance().displayImage(url, imageViewAware, options, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
            } else {
                try {
                    BitmapFactory.Options opt = new BitmapFactory.Options();
                    opt.inSampleSize = 1;
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), opt);
                    options.getDisplayer().display(bitmap, imageViewAware, LoadedFrom.DISC_CACHE);
                } catch (Exception var8) {
                    var8.printStackTrace();
                }
            }
        }

    }

    protected void onDestroy() {
        RLog.d("AMapRealTimeActivity", "onDestroy()");
        this.mAMapView.onDestroy();
        LocationManager.getInstance().setLocationChangedListener((ILocationChangedListener)null);
        super.onDestroy();
    }

    private AMapRealTimeActivity.UserTarget createUserTargetById(String userId) {
        if (this.mUserTargetMap.get(userId) != null) {
            return (AMapRealTimeActivity.UserTarget)this.mUserTargetMap.get(userId);
        } else {
            AMapRealTimeActivity.UserTarget userTarget = new AMapRealTimeActivity.UserTarget();
            userTarget.targetView = new ImageView(this);
            userTarget.targetView.setTag(userId);
            userTarget.targetView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String userId = (String)v.getTag();
                    AMapRealTimeActivity.UserTarget user = (AMapRealTimeActivity.UserTarget)AMapRealTimeActivity.this.mUserTargetMap.get(userId);
                    LatLng latLng = user.targetMarker.getPosition();
                    if (latLng != null) {
                        CameraUpdate update = CameraUpdateFactory.changeLatLng(latLng);
                        AMapRealTimeActivity.this.mAMap.animateCamera(update, (AMap.CancelableCallback)null);
                    }

                }
            });
            float scale = Resources.getSystem().getDisplayMetrics().density;
            int hw = (int)(40.0F * scale + 0.5F);
            int pd = (int)(2.0F * scale + 0.5F);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(hw, hw);
            userTarget.targetView.setLayoutParams(lp);
            userTarget.targetView.setPadding(pd, pd, pd, pd);
            this.setAvatar(userTarget.targetView, (String)null);
            this.mTitleBar.addView(userTarget.targetView);
            View iconView = LayoutInflater.from(this).inflate(R.layout.rc_icon_rt_location_marker, (ViewGroup)null);
            ImageView locImageView = (ImageView)iconView.findViewById(16908295);//@android:id/icon1
            ImageView avatar = (ImageView)iconView.findViewById(16908294);
            this.setAvatar(avatar, (String)null);
            if (userId.equals(RongIMClient.getInstance().getCurrentUserId())) {
                locImageView.setImageResource(R.drawable.rc_rt_loc_myself);
            } else {
                locImageView.setImageResource(R.drawable.rc_rt_loc_other);
            }

            MarkerOptions markerOptions = (new MarkerOptions()).anchor(0.5F, 0.5F).icon(BitmapDescriptorFactory.fromView(iconView));
            userTarget.targetMarker = this.mAMap.addMarker(markerOptions);
            return userTarget;
        }
    }

    private void removeParticipantTitleIcon(final AMapRealTimeActivity.UserTarget userTarget) {
        this.mHandler.post(new Runnable() {
            public void run() {
                AMapRealTimeActivity.this.mTitleBar.removeView(userTarget.targetView);
            }
        });
    }

    private void updateParticipantTitleText() {
        this.mHandler.post(new Runnable() {
            public void run() {
                if (AMapRealTimeActivity.this.mUserTargetMap.size() != 0) {
                    if (AMapRealTimeActivity.this.mUserTargetMap.size() == 1) {
                        AMapRealTimeActivity.this.mUserText.setText(AMapRealTimeActivity.this.getResources().getString(R.string.rc_you_are_sharing_location));
                    } else {
                        AMapRealTimeActivity.this.mUserText.setText(String.format(AMapRealTimeActivity.this.getResources().getString(R.string.rc_others_are_sharing_location), AMapRealTimeActivity.this.mUserTargetMap.size()));
                    }

                }
            }
        });
    }

    private void updateParticipantMarker(double latitude, double longitude, String userId) {
        AMapRealTimeActivity.UserTarget target = (AMapRealTimeActivity.UserTarget)this.mUserTargetMap.get(userId);
        if (target == null) {
            target = this.createUserTargetById(userId);
            this.mUserTargetMap.put(userId, target);
            LocationManager.getInstance().getUserInfo(userId, this);
            if (!this.mParticipants.contains(userId)) {
                this.mParticipants.add(userId);
            }
        }

        target.targetMarker.setPosition(new LatLng(latitude, longitude));
        this.updateParticipantTitleText();
        if (userId.equals(RongIMClient.getInstance().getCurrentUserId()) && !this.mHasAnimate && latitude != 0.0D && longitude != 0.0D) {
            CameraUpdate update = CameraUpdateFactory.changeLatLng(new LatLng(latitude, longitude));
            this.mAMap.animateCamera(update, (AMap.CancelableCallback)null);
            this.mHasAnimate = true;
        }

    }

    private void removeParticipantMarker(AMapRealTimeActivity.UserTarget userTarget) {
        userTarget.targetMarker.remove();
    }

    private class UserTarget {
        public ImageView targetView;
        public Marker targetMarker;

        private UserTarget() {
        }
    }
}

